package com.yonyou.cyxdms.sysAuth.service.service.dealerchannel;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.yonyou.cloud.http.plus.domain.MessEvent;
import com.yonyou.cloud.http.plus.remote.IRemoteInvoke;
import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.service.http.HttpRequestService;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.framework.util.http.RestHttpUtil;
import com.yonyou.cyx.function.bean.dto.http.RestServiceRequestDto;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyxdms.basedata.client.domains.vo.BrandCacheVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.RegionVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.SeriesCacheVO;
import com.yonyou.cyxdms.basedata.client.dto.RegionConditionDTO;
import com.yonyou.cyxdms.basedata.client.feign.BaseDataCommonClient;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonBrandService;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonRegionService;
import com.yonyou.cyxdms.basedata.client.service.basedata.BaseCommonSeriesService;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.CommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.dealerchannel.DealerDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.dealerchannel.DealerDetailDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.dealerchannel.DealerInfoDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.dealerchannel.DealerListDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.*;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import com.yonyou.cyxdms.sysAuth.service.service.SystemParamService;
import com.yonyou.cyxdms.sysAuth.service.service.org.OrgService;
import com.yonyou.cyxdms.sysAuth.service.vo.companyorg.DealerOrgAreaVO;
import com.yonyou.cyxdms.sysAuth.service.vo.companyorg.DealerPageVO;
import com.yonyou.cyxdms.sysAuth.service.vo.dealerchannel.DealerOrgVO;
import com.yonyou.cyxdms.sysAuth.service.vo.dealerchannel.SaleInfoVO;
import com.yonyou.cyxdms.sysAuth.service.vo.org.OrgBrandSeriesVO;
import com.yonyou.cyxdms.sysmanage.client.vo.dealer.DealerInfoAVO;
import com.yonyou.cyxdms.sysmanage.client.vo.dealer.DealerInfoParentVO;
import com.yonyou.cyxdms.sysmanage.client.vo.dealer.DealerOrAscOrCompanyVO;
import com.yonyou.cyxdms.sysmanage.client.vo.dealer.DealerPictureVO;
import com.yonyou.cyxdms.sysmanage.client.vo.org.OrgParentVO;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhangsx
 * @since 2018-10-22
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DealerInfoServiceImpl extends ServiceImpl<DealerInfoMapper, DealerInfoPO> implements DealerInfoService {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(DealerInfoServiceImpl.class);

    @Resource
    DealerInfoMapper dealerInfoMapper;

    @Autowired
    HttpRequestService requestService;

    @Value("${obtainDealer}")
    private String obtainDealer;

    @Value("${dealer.picture}")
    private String dealerPictureUrl;

    @Autowired
    OrgService orgService;

    @Resource
    private OrgMapper orgMapper;
    @Autowired
    BaseCommonBrandService baseCommonBrandService;
    @Autowired
    BaseCommonSeriesService baseCommonSeriesService;

    @Autowired
    private IRemoteInvoke iRemoteInvoke;


    @Resource
    TrDealerOrgRelationMapper trDealerOrgRelationMapper;


    @Resource
    private TrOrgMapper trOrgMapper;

    @Resource
    private CompanyMapper companyMapper;

    @Autowired
    private BaseDataCommonClient baseDataCommonClient;


    @Autowired
    private SystemParamService systemParamService;

    @Value("dealer.picture")
    private String defaultDealerPicture;

    @Autowired
    BaseCommonRegionService baseCommonRegionService;

    /**
     * 将LocalDateTime转为Long类型的timestamp
     *
     * @param localDateTime
     * @return java.lang.Integer
     * @author zhangsx
     * @since 2018/9/19
     */
    public static Long getTimestampOfDateTime(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = localDateTime.atZone(zone).toInstant();
        return instant.toEpochMilli();
    }

    /**
     * 分页查询对应数据
     *
     * @param page           分页对象
     * @param queryCondition 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage
     * @author zhangsx
     * @since 2018/7/22 0022
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        // 获取总条数
        page.setRecords(dealerInfoMapper.selectPageBySql(page, queryCondition));
        return page;
    }

    /**
     * 根据查询条件返回结果集
     *
     * @param queryCondition 查询条件
     * @return java.util.List
     * @author zhangsx
     * @since 2018/7/22 0022
     */
    @Override
    @Transactional(readOnly = true)
    public List<Map<String, Object>> selectListBySql(Map<String, Object> queryCondition) {
        return dealerInfoMapper.selectListBySql(queryCondition);
    }

//    /**
//     * 根据DTO 进行数据新增
//     *
//     * @param dealerInfoDTO 页面DTO
//     * @return void
//     * @author zhangxianchao
//     * @since 2018/7/21 0021
//     */
//    @Override
//    public Map<String, Object> insert(DealerBasicinfoPO dealerInfoDTO) {
//        //对对象进行赋值操作
//        DealerBasicinfoPO dealerInfoPO = dealerInfoDTO.transDtoToPo(DealerBasicinfoPO.class);
//        //执行插入
//        dealerInfoMapper.insert(dealerInfoPO);
//        //返回插入的值
//        return dealerInfoMapper.selectById(dealerInfoPO.getDealerId()).toMaps();
//    }

    /**
     * 根据查询条件返回结果集
     *
     * @param id
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author zhangsx
     * @since 2019/1/9
     */
    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getById(Long id) {
        DealerInfoPO dealerinfopo = dealerInfoMapper.selectById(id);
        if (dealerinfopo != null) {
            DealerBasicinfoPO po = new DealerBasicinfoPO(dealerinfopo);
            return po.toMaps();
        } else {
            throw new DALException("查询失败，没有符合条件的数据");
        }
    }

    /**
     * 根据DTO 及ID 进行数据更新
     *
     * @param id            主键ID
     * @param dealerInfoDTO 页面DTO
     * @return void
     * @author zhangxianchao
     * @since 2018/7/21 0021
     */
    @Override
    public Map<String, Object> update(Long id, DealerInfoDTO dealerInfoDTO) {
        DealerInfoPO dealerinfopo = dealerInfoMapper.selectById(id);
        //对对象进行赋值操作
        dealerInfoDTO.transDtoToPo(dealerinfopo);
        //执行更新
        dealerInfoMapper.updateById(dealerinfopo);
        return dealerinfopo.toMaps();
    }

    /**
     * dms过来的经销商信息---新增
     *
     * @param dealerInfoDTO
     * @return java.lang.Long
     * @author zhangsx
     * @since 2018/10/22
     */
    @Override
    public Long insertDealerInfoFromDms(DealerInfoDTO dealerInfoDTO) {
        // 由于逻辑修改，需要增加一条同样信息的数据到company表
        logger.debug("经销商新增数据dealerInfoDTO:{}", dealerInfoDTO);
        CompanyPO companypo = new CompanyPO();
        companypo.setAddressCn(dealerInfoDTO.getAddress());
        companypo.setAppId(dealerInfoDTO.getAppId());
        companypo.setCityId(dealerInfoDTO.getCityId());
        companypo.setIsFixed(ManageDictCodeConstants.NO_IS_LOCK);
        companypo.setCompanyCode(dealerInfoDTO.getDealerCode());
        companypo.setCompanyNameCn(dealerInfoDTO.getDealerFullName());
        companypo.setCompanyShortNameCn(dealerInfoDTO.getDealerShortName());
        companypo.setCompanyType(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY);
//        companyPO.setCounty(dealerInfoDTO.getCountyId());
        companypo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_SUPER);
        companypo.seteMail(dealerInfoDTO.getDealerEmail());
//        companyPO.setOrgId(Integer.MAX_VALUE);
        companypo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
        companypo.setFax(dealerInfoDTO.getFaxNo());
        companypo.setPhone(dealerInfoDTO.getPhone());
        companypo.setIsDeleted(0);

        companyMapper.insert(companypo);
        logger.debug("新增经销商公司信息：{}", companypo);
        logger.info("新增经销商信息:{}", dealerInfoDTO);

        DealerInfoPO dealerinfopo = new DealerInfoPO();
//        dealerInfoPO.setCompanyId(companyPO.getCompanyId());
        dealerinfopo.setCityId(dealerInfoDTO.getCityId());
        dealerinfopo.setAddress(dealerInfoDTO.getRegAddress());
        dealerinfopo.setEmail(dealerInfoDTO.getDealerEmail());
        dealerinfopo.setFaxNo(dealerInfoDTO.getDealerFaxNumber());
        dealerinfopo.setLongitude(dealerInfoDTO.getLongitude());
        dealerinfopo.setLatitude(dealerInfoDTO.getLatitude());
        dealerinfopo.setPhone(dealerInfoDTO.getServicePhone());

        dealerinfopo.setOrgId(0);
        dealerinfopo.setDealerCode(dealerInfoDTO.getDealerCode());
        dealerinfopo.setDealerName(dealerInfoDTO.getDealerFullName());
        dealerinfopo.setDealerShortname(dealerInfoDTO.getDealerShortName());
        dealerinfopo.setAppId(dealerInfoDTO.getAppId());
        dealerinfopo.setCreatedAt(LocalDateTime.now());
        dealerinfopo.setIsDeleted(0);
        //没有符合条件条数据---新增操作---返回主键id
        dealerInfoMapper.save(dealerinfopo);
        //执行新增操作---获取返回的主键dealerId
        return Long.parseLong(String.valueOf(dealerinfopo.getDealerId()));
    }

    /**
     * 更新来自dms的经销商信息
     *
     * @param dto
     * @return void
     * @author zhangsx
     * @since 2018/10/31
     */
    @Override
    public void updateDealerInfoFromDms(DealerInfoDTO dto) {
        DealerInfoPO dealerinfopo = new DealerInfoPO();
        //对对象进行赋值操作
        BeanUtils.copyProperties(dto, dealerinfopo);
        logger.debug("获取dealerInfoDTO的信息dealerInfoPO:{}", dealerinfopo);
        //根据的appid 和 dealercode获取company明细
        LambdaQueryWrapper<CompanyPO> queryWrapper = new QueryWrapper<CompanyPO>().lambda();
        queryWrapper.eq(CompanyPO::getAppId, dto.getAppId());
        queryWrapper.eq(CompanyPO::getCompanyCode, dto.getDealerCode());
        CompanyPO companypo = companyMapper.selectOne(queryWrapper);
        logger.debug("经销商公司信息companyPO:{}", companypo);
        if (companypo == null) {
            throw new ServiceBizException("根据dealerCode,appId查询companyPO信息失败！");
        }
        companypo.setAddressCn(dto.getAddress());
        companypo.setCityId(dto.getCityId());
        companypo.setCompanyCode(dto.getDealerCode());
        companypo.setCompanyNameCn(dto.getDealerFullName());
        companypo.setCompanyShortNameCn(dto.getDealerShortName());
        companypo.setCompanyType(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY);
        companypo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_SUPER);
        companypo.seteMail(dto.getDealerEmail());
        companypo.setFax(dto.getFaxNo());
        companypo.setPhone(dto.getPhone());
        companypo.setUpdatedAt(LocalDateTime.now());
        companyMapper.updateById(companypo);
        //没有符合条件条数据---新增操作---返回主键id
        dealerinfopo.setLongitude(dto.getLongitude());
        dealerinfopo.setLatitude(dto.getLatitude());
        dealerinfopo.setDealerName(dto.getDealerFullName());
        dealerinfopo.setDealerShortname(companypo.getCompanyShortNameCn());
//        dealerInfoPO.setCompanyId(companyPO.getCompanyId());
        dealerinfopo.setCreatedBy(companypo.getCreatedBy());
        dealerinfopo.setUpdatedAt(companypo.getUpdatedAt());
        dealerinfopo.setUpdatedBy(companypo.getUpdatedBy());
        dealerinfopo.setRecordVersion(companypo.getRecordVersion() + 1);
        updateById(dealerinfopo);
    }

    @Override
    public void updateDealerInfoFromDmss(Long id, DealerInfoDTO dealerInfoDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long factoryCompanyId = companyMapper.findFactoryIdByAppId(loginInfoDto.getAppId());
        if (null == factoryCompanyId) {
            throw new ServiceBizException("您输入的AppID可能不存在");
        }

        DealerInfoPO dealerinfopo = dealerInfoMapper.selectById(id);
        //对对象进行赋值操作
        BeanMapperUtil.copyPropertiesWithOutNull(dealerInfoDTO, dealerinfopo);
        dealerinfopo.setFactoryCompanyId(factoryCompanyId.intValue());
        dealerinfopo.setDealerShortname(dealerInfoDTO.getDealerShortName());
        trDealerOrgRelationMapper.deleteById(dealerinfopo.getOrgId());
        List<OrgBrandSeriesVO> list = dealerInfoDTO.getListOBSVO();
        if (list != null && list.size() > 0) {
            for (OrgBrandSeriesVO orgBrandSeriesVO : list) {
                TrDealerOrgRelationPO trDealePo = new TrDealerOrgRelationPO();
                if (null != orgBrandSeriesVO) {
                    if (orgBrandSeriesVO.getBillType() == SysAuthDictCodeConstants.BILL_TYPE_ORG_RELATION_BRAND) {
                        //存品牌id
                        trDealePo.setBillId(orgBrandSeriesVO.getBrandId().intValue());
                    } else { //存车系id
                        trDealePo.setBillId(orgBrandSeriesVO.getSeriesId().intValue());
                    }
                    trDealePo.setBillType(orgBrandSeriesVO.getBillType().intValue());
                    trDealePo.setOrgId(dealerinfopo.getOrgId());
                    trDealePo.setCreatedBy(loginInfoDto.getUserName());
                    trDealePo.setUpdatedBy(loginInfoDto.getUserName());
                    trDealerOrgRelationMapper.addAuthorizedBrand(trDealePo);
                }
            }

        }
        //执行更新
        dealerInfoMapper.updateById(dealerinfopo);
        OrgPO orgpo = orgMapper.selectById(dealerinfopo.getOrgId().longValue());
        orgpo.setOrgName(dealerInfoDTO.getDealerName());
        orgpo.setOrgShortName(dealerInfoDTO.getDealerShortName());
        orgMapper.updateById(orgpo);

        if (!StringUtils.isNullOrEmpty(dealerInfoDTO.getSaleArea())) {
            //删除原来的上级组织
            orgService.deleteById(dealerinfopo.getOrgId().longValue(), loginInfoDto.getCompanyId());
            //新增组织关系
            TrOrgPO po = new TrOrgPO();
            po.setOrgId(dealerinfopo.getOrgId().longValue());
            po.setParentOrgId(Long.parseLong(dealerInfoDTO.getSaleArea()));
            trOrgMapper.insert(po);
        }

        // add
        CompanyPO company = companyMapper.selectById(dealerInfoDTO.getCompanyId());
        String companyCode = "";
        if (company != null) {
            companyCode = company.getCompanyCode();
        }
        Map<String, Object> data = new HashMap<>();
        data.put("appId", loginInfoDto.getAppId());
        data.put("ownerCode", dealerInfoDTO.getDealerCode());
        data.put("ownerParCode", dealerInfoDTO.getDealerCode());
        data.put("companyCode", companyCode);
        data.put("orgId", "");
        //远程调用对象：url / body参数（json）/  header
        MessEvent messEvent = new MessEvent();
        String channel = "sysParam";
        messEvent.setUrl("http://OPS-NOTIFY/notify/invoke/message?channel=" + channel);
        messEvent.setParam(data);
        messEvent.setHeaders(null);
        //远程调用
        iRemoteInvoke.sendPostWithTransaction(messEvent);
    }

    /**
     * 通过dealerCode获取dealerId
     *
     * @param dealerCode
     * @return java.lang.Long
     * @author zhangsx
     * @since 2018/11/12
     */
    @Override
    public Long getDealerIdByDealerCode(String dealerCode) {
        logger.info("获取dealerId开始---------------");
        LambdaQueryWrapper<DealerInfoPO> queryWrapper = new QueryWrapper<DealerInfoPO>().lambda();
        queryWrapper.eq(DealerInfoPO::getDealerCode, dealerCode);
        DealerInfoPO result = getOne(queryWrapper);
        logger.info("dealerCode对应的dealerId ：{}", result.getDealerId());
        return Long.parseLong(String.valueOf(result.getDealerId()));
    }

    /**
     * 根据dealerId查询dealerCode
     *
     * @author dengqiang
     * @since 2019/1/4
     */
    @Override
    public String getDealerCodeByDealerId(Long dealerId) {

        LambdaQueryWrapper<DealerInfoPO> queryWrapper = new QueryWrapper<DealerInfoPO>().lambda();
        queryWrapper.eq(DealerInfoPO::getDealerId, dealerId);
        DealerInfoPO dealerinfopo = getOne(queryWrapper);
        if (dealerinfopo != null) {
            return dealerinfopo.getDealerCode();
        } else {
            throw new ServiceBizException("根据dealerId查询dealerCode异常");
        }
    }

    /**
     * 根据dealerCode获取经销商信息
     *
     * @param dealerCode
     * @param appId
     * @return com.yonyou.cyx.dealer.service.entity.dto.dealerinfo.DealerInfoDTO
     * @author zhangsx
     * @since 2019/1/9
     */
    @Override
    public DealerInfoDTO getDealerInfoByCode(String dealerCode, String appId) {
        QueryWrapper<DealerInfoPO> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(DealerInfoPO::getAppId, appId);
        wrapper.lambda().eq(DealerInfoPO::getDealerCode, dealerCode);
        wrapper.lambda().eq(DealerInfoPO::getIsDeleted, 0);
        DealerInfoPO res = this.getOne(wrapper);
        try {
            return BeanMapperUtil.copyProperties(res, DealerInfoDTO.class);
        } catch (Exception e) {
            logger.debug("DealerInfoServiceImpl getDealerInfoByCode {},dealerCode={},appId={}", e, dealerCode, appId);
            throw new ServiceBizException("根据dealerCode appId查询dealer异常");
        }
    }

    @Override
    public List<DealerInfoDTO> dealerInfoList(DealerListDTO dealerListDTO) {
        Page<Map<String, Object>> page = new Page(dealerListDTO.getCurrentPage(), dealerListDTO.getPageSize());
        List<DealerInfoDTO> dealerinfodtos = null;
        LoginInfoDto login = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        String dealerListUrl = systemParamService.getParamValueByCode(CommonConstants.DEALER_LIST, login.getAppId());
        if (StringUtils.isNullOrEmpty(dealerListUrl)) {
            dealerinfodtos = dealerInfoMapper.dealerInfoList(page, dealerListDTO);
            if (!CommonUtils.isNullOrEmpty(dealerinfodtos)) {
                dealerinfodtos.stream().forEach(m -> {
                    if (m.getBusinessBeginHours() == null) {
                        m.setBusinessBeginHours("");
                    }
                    if (m.getBusinessEndHours() == null) {
                        m.setBusinessEndHours("");
                    }
                    if (m.getDealerName() == null) {
                        m.setDealerName("");
                    }

                    StringBuilder dealerFullAddress = new StringBuilder();
                    if (!StringUtils.isNullOrEmpty(m.getProvinceId())) {
                        RegionVO vo = baseCommonRegionService.dataByRegionId(Long.valueOf(m.getProvinceId()));
                        if (vo != null) {
                            dealerFullAddress.append(vo.getRegionName());
                        }
                    }
                    if (!StringUtils.isNullOrEmpty(m.getCityId())) {
                        RegionVO vo = baseCommonRegionService.dataByRegionId(Long.valueOf(m.getCityId()));
                        if (vo != null) {
                            dealerFullAddress.append(vo.getRegionName());
                        }
                    }
                    if (!StringUtils.isNullOrEmpty(m.getCountyId())) {
                        RegionVO vo = baseCommonRegionService.dataByRegionId(Long.valueOf(m.getCountyId()));
                        if (vo != null) {
                            dealerFullAddress.append(vo.getRegionName());
                        }
                    }
                    m.setRegAddress(dealerFullAddress.toString() + m.getRegAddress());
                });
            }
        } else {
            //远端调用 字段解析
            RestTemplate temp = new RestTemplate();
            String response = RestHttpUtil.get(temp, dealerListUrl, String.class);
            logger.info("调用远端经销商列表：{}", response);
            //TODO JSON解析  赋值

        }

        return dealerinfodtos;
    }

    @Override
    public DealerInfoDTO dealerDetailInfo(DealerDetailDTO detail) {
        DealerInfoDTO dealerInfoDTO = null;
        LoginInfoDto login = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String dealerDetail = systemParamService.getParamValueByCode(CommonConstants.DEALER_DETAIL, login.getAppId());
        if (StringUtils.isNullOrEmpty(dealerDetail)) {
            //根据dealerId获取经销商信息
            dealerInfoDTO = dealerInfoMapper.dealerDetailInfo(detail);
            if (dealerInfoDTO != null && StringUtils.isNullOrEmpty(dealerInfoDTO.getDealerPicture())) {
                dealerInfoDTO.setDealerPicture(defaultDealerPicture);
            }

            if (dealerInfoDTO.getBusinessBeginHours() == null) {
                dealerInfoDTO.setBusinessBeginHours("");
            }
            if (dealerInfoDTO.getBusinessEndHours() == null) {
                dealerInfoDTO.setBusinessEndHours("");
            }
            if (dealerInfoDTO.getDealerName() == null) {
                dealerInfoDTO.setDealerName("");
            }

            StringBuilder dealerFullAddress = new StringBuilder();
            try {
                if (!StringUtils.isNullOrEmpty(dealerInfoDTO.getProvinceId())) {
                    RegionVO vo = baseCommonRegionService.dataByRegionId(Long.valueOf(dealerInfoDTO.getProvinceId()));
                    if (vo != null) {
                        dealerFullAddress.append(vo.getRegionName());
                    }
                }
                if (!StringUtils.isNullOrEmpty(dealerInfoDTO.getCityId())) {
                    RegionVO vo = baseCommonRegionService.dataByRegionId(Long.valueOf(dealerInfoDTO.getCityId()));
                    if (vo != null) {
                        dealerFullAddress.append(vo.getRegionName());
                    }
                }
                if (!StringUtils.isNullOrEmpty(dealerInfoDTO.getCountyId())) {
                    RegionVO vo = baseCommonRegionService.dataByRegionId(Long.valueOf(dealerInfoDTO.getCountyId()));
                    if (vo != null) {
                        dealerFullAddress.append(vo.getRegionName());
                    }
                }
                logger.debug("补充省市信息：{}", dealerFullAddress.toString());
                dealerInfoDTO.setRegAddress(dealerFullAddress.toString() + dealerInfoDTO.getRegAddress());
            } catch (Exception e) {
                logger.error("经销商地址获取失败！", e);
                throw new ServiceBizException("经销商地址获取失败！");
            }
        } else {
            //远端调用 字段解析
            RestTemplate temp = new RestTemplate();
            String response = RestHttpUtil.get(temp, dealerDetail, String.class);
            logger.info("调用远端经销商详情：{}", response);
            //TODO JSON解析  赋值
        }

        logger.info("数据库中查询出来的经销商信息：{}", dealerInfoDTO);
        return dealerInfoDTO;
    }

    /**
     * //根据经销商ID查询在售品牌列表
     *
     * @author dengqiang
     * @since 2019/2/14
     */
    @Override
    public List<Long> getSaleCarbrandIdList(Long dealerId, String appId) {
        return dealerInfoMapper.getSaleCarbrandIdList(dealerId, appId);
    }

    /**
     * 根据经销商id获取经销商试驾地址
     *
     * @author dengqiang
     * @since 2019/2/14
     */
    @Override
    public String getDriveAddress(Long dealerId) {
        return dealerInfoMapper.getDriveAddress(dealerId);
    }

    /* *
     * 经销商名称(根据appId和dearCode可以确定唯一性)
     *
     * @author dengqiang
     * @since 2019/5/16
     */
    @Override
    public String getDealerName(String appId, String dealerCode) {
        DealerInfoPO dealerinfopo = dealerInfoMapper.getDealerCode(appId, dealerCode);
        return dealerinfopo.getDealerName();
    }

    /**
     * 无条件获取经销商
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/8/16
     */
    @Override
    public List<DealerDTO> getDealer(Long currentPage, Long size) {
        IPage page = new Page();
        page.setCurrent(currentPage);
        page.setSize(size);
        LambdaQueryWrapper<DealerInfoPO> query = new QueryWrapper<DealerInfoPO>().lambda();
        IPage<DealerInfoPO> iPage = dealerInfoMapper.selectPage(page, query);
        List<DealerInfoPO> records = iPage.getRecords();
        return BeanMapperUtil.copyList(records, DealerDTO.class);
    }

    /**
     * @description：获取修改的经销商
     * @author ：quankk
     * @date ：Created in 2019/1/22 11:41
     * @modified By：
     */
    @Override
    public String obtainDealer() {
        DealerInfoPO dealerbasicinfopo =
                dealerInfoMapper.selectPage(new Page<>(1, 1), new QueryWrapper<>()).getRecords().get(0);
        DealerDTO result = new DealerDTO();
        BeanUtils.copyProperties(dealerbasicinfopo, result);

        //创建时间
        result.setCreatedDate(dealerbasicinfopo.getCreatedAt());
        Gson gson = new Gson();
        String body = gson.toJson(result);
        RestServiceRequestDto restDto = new RestServiceRequestDto(obtainDealer, body);
        return requestService.postJsonRequest(restDto).getResponseMsg();
    }

    @Override
    public DealerOrAscOrCompanyVO getDealerOrAscOrCompany(String ownerCode) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<DealerOrAscOrCompanyVO> dealerorascorcompanyvos = new ArrayList<>();
        if (ownerCode == null) {
            ownerCode = loginInfoDto.getOwnerCode();
        }
        dealerorascorcompanyvos = dealerInfoMapper.getDealerByCode(ownerCode);
        if (dealerorascorcompanyvos.size() != 1) {
            dealerorascorcompanyvos = dealerInfoMapper.getAscByCode(ownerCode);
            if (dealerorascorcompanyvos.size() != 1) {
                dealerorascorcompanyvos = dealerInfoMapper.getCompanyByCode(ownerCode);
            }
        }
        return dealerorascorcompanyvos.get(0);
    }

    /**
     * 保存经销商信息
     *
     * @auther: 李贺
     * @since: 2019/9/10
     */
    @Override
    public void addDealerInfo(DealerInfoPO dealerinfopo) {
        dealerInfoMapper.insert(dealerinfopo);
    }

    /**
     * 更新经销商信息
     *
     * @auther: 李贺
     * @since: 2019/9/16
     */
    @Override
    public void updateDealerById(DealerInfoPO dealerinfopo) {
        dealerInfoMapper.updateById(dealerinfopo);
    }

    @Override
    public DealerInfoPO selectById(Integer dealerId) {
        return dealerInfoMapper.selectById(dealerId);
    }


    /**
     * 批量查询dealer信息
     *
     * @param ownerCodes  模拟查询id与name
     * @param isBlack     true:not in  , false:in
     * @param appId
     * @param currentPage
     * @param pageSize
     * @return:
     * @auther: tanjie
     * @since: 2019/9/23
     */
    @Override
    public List<Map<String, String>> getDealerInfoByCodes(List<String> ownerCodes, Boolean isBlack, String appId,
                                                          String ownerCode, String orgId, Integer currentPage, Integer pageSize,
                                                          Long companyId) {
        LoginInfoDto login = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        login.setAppId(appId);
        login.setCompanyId(companyId);

/*
            if (isBlack) {  //不在黑名单里。 not in ownercodes

                if (!StringUtils.isNullOrEmpty(orgId)) {
                    List<DealerOrgAreaVO> dealerBySaleArea = this.getDealerBySaleArea(orgId, null, null);
                    logger.info("不在黑名单中");
                    for (int i = dealerBySaleArea.size() - 1; i >= 0; i--) {
                        DealerOrgAreaVO dealerOrgAreaVO = dealerBySaleArea.get(i);
                        for (int j = ownerCodes.size() - 1; j >= 0; j--) {
                            String blackowner = ownerCodes.get(j);
                            if (blackowner.equals(dealerOrgAreaVO.getDealerCode())) {
                                ownerCodes.remove(j);
                            }
                        }
                    }

                    isBlack = false;
                } else {
                    isBlack = true;
                }

            } else {  //在黑名单 中 in ownerCodes
                logger.info("在黑名单中");
                if (!StringUtils.isNullOrEmpty(orgId)) {
                    List<DealerOrgAreaVO> dealerBySaleArea = this.getDealerBySaleArea(orgId, null, null);
                    List<String> dealerList = dealerBySaleArea.stream().map(e -> e.getDealerCode()).collect(Collectors.toList());
                    for (int i = ownerCodes.size() - 1; i >= 0; i--) {
                        String inList = ownerCodes.get(i);
                        for (int j = dealerList.size() - 1; j >= 0; j--) {
                            String inBlack = dealerList.get(i);
                            if (!inList.equals(inBlack)) {
                                dealerList.remove(i);
                            }
                        }
                    }
                    ownerCodes.clear();
                    ownerCodes.addAll(dealerList);
                    if (ownerCodes == null) { //在黑名单中 但是没有搜索条件
                        return null;
                    }
                    isBlack = false;

                } else {
                    isBlack = false;
                }

        }*/
        Integer start = (currentPage - 1) * pageSize;
        List<Map<String, String>> result = this.dealerInfoMapper.getDealerInfoByCodes(ownerCodes, isBlack, appId,
                ownerCode, start, pageSize, orgId);

        List total = this.dealerInfoMapper.getTotalDealerInfoByCodes(ownerCodes, isBlack, appId,
                ownerCode, orgId);

        for (Map<String, String> stringStringMap : result) {
            stringStringMap.put("TOTAL", total == null ? null : String.valueOf(total.size()));
        }
        return result;
    }


    /**
     * 获取经销商上级code
     *
     * @param ownerCode
     * @return:
     * @auther: tanjie
     * @since: 2019/9/24
     */
    @Override
    public Map<String, String> getDealerHeightLevelCode(String ownerCode, String appId) {
        if (null == appId || appId.trim() == "") {
            throw new ServiceBizException("未传入appId");
        }
        return dealerInfoMapper.getDealerHeightLevelCode(appId, ownerCode);
    }

    @Override
    public IPage<DealerPageVO> getDealerByParam(Page<DealerPageVO> page, String dealerName) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> param = new HashMap<>();
        if (!StringUtils.isNullOrEmpty(dealerName)) {
            param.put("dealerName", dealerName.trim());
        }
        //param.put("cityId", cityId);
        param.put("companyId", loginInfoDto.getCompanyId());
        param.put("appId", loginInfoDto.getAppId());

        List<Long> cityIds = new ArrayList<>();
        if (!StringUtils.isNullOrEmpty(dealerName)) {
            RegionConditionDTO regionConditionDTO = new RegionConditionDTO();
            regionConditionDTO.setRegionName(dealerName);
            regionConditionDTO.setIsLike(1);
            regionConditionDTO.setRegionLevel(2);
            RestResultResponse<List<Long>> regionIdList = baseDataCommonClient.getRegionIdList(regionConditionDTO);
            cityIds = regionIdList.getData();
        }

        List<DealerPageVO> list = new ArrayList<>();

        list = dealerInfoMapper.getDealerByParam(page, param, cityIds);
        Map<Long, String> regionMap = new HashMap<>();
        List<Long> longs = new ArrayList<>();
        for (DealerPageVO dealerPageVO : list) {
            longs.add(dealerPageVO.getProvinceId());
            longs.add(dealerPageVO.getCityId());
            longs.add(dealerPageVO.getCountyId());
        }
        if (longs == null || longs.size() == 0) {
            return null;
        }
        RestResultResponse<List<RegionVO>> provinceRelatedData = baseDataCommonClient.getProvinceRelatedData(longs);
        List<RegionVO> regionvos = provinceRelatedData.getData();

        for (RegionVO regionVO : regionvos) {
            Long regionId = regionVO.getRegionId();
            String regionName = regionVO.getRegionName();
            regionMap.put(regionId, regionName);
        }
        for (DealerPageVO dealerPageVO : list) {
            dealerPageVO.setAddress(regionMap.get(dealerPageVO.getProvinceId()) + regionMap.get(dealerPageVO.getCityId()) + regionMap.get(dealerPageVO.getCountyId()) + dealerPageVO.getAddress());
        }
        page.setRecords(list);
        return page;
    }

    /**
     * 获取销售公司信息
     *
     * @auther: 李贺
     * @since: 2019/10/9
     */
    @Override
    public IPage<SaleInfoVO> getSaleInfo(Page<SaleInfoVO> page) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appId = loginInfoDto.getAppId();
        List<SaleInfoVO> saleinfovos = dealerInfoMapper.querySaleInfoListByAppId(page, appId, ManageDictCodeConstants.ORG_TYPE_FACTORY);
        page.setRecords(saleinfovos);
        return page;
    }

    @Override
    @Transactional
    public void addSaleInfo(SaleInfoVO saleInfoVO) {

        Long companyId = saleInfoVO.getCompanyId();
        CompanyPO companypo1 = new CompanyPO();
        if (companyId != null) {
            companypo1 = companyMapper.selectById(companyId);
        }

        if (companypo1 == null) {
            //新增
            CompanyPO companypo = BeanMapperUtil.copyProperties(saleInfoVO, CompanyPO.class);
            companypo.setOrgId(0);
            companyMapper.insert(companypo);
            //新增tmOrg
            OrgPO orgpo = new OrgPO();
            orgpo.setOrgId(Long.MAX_VALUE);
            addSaleOrg(companypo, orgpo);
            orgMapper.insert(orgpo);

//            companyPO.setOrgId(orgPO.getOrgId().intValue());
            companyMapper.updateById(companypo);

        } else {
            //修改
            CompanyPO companypo = companyMapper.selectById(companyId);
            BeanMapperUtil.copyProperties(saleInfoVO, companypo);
//            companyPO.setCounty(saleInfoVO.getCounty().toString());
            companyMapper.updateById(companypo);
            LambdaQueryWrapper<OrgPO> orgQuery = new QueryWrapper<OrgPO>().lambda();
            orgQuery.eq(OrgPO::getOrgId, companypo.getOrgId());
            OrgPO orgpo = orgMapper.selectOne(orgQuery);
            orgpo.setOrgName(companypo.getCompanyNameCn());
            orgpo.setOrgShortName(companypo.getCompanyShortNameCn());
            orgMapper.updateById(orgpo);
        }
    }

    private void addSaleOrg(CompanyPO companypo, OrgPO orgpo) {
        orgpo.setAppId(companypo.getAppId());
        orgpo.setCompanyId(companypo.getCompanyId().longValue());
        orgpo.setOrgCode(companypo.getCompanyCode());
        orgpo.setOrgName(companypo.getCompanyNameCn());
        orgpo.setOrgShortName(companypo.getCompanyShortNameCn());
        orgpo.setOrgType(ManageDictCodeConstants.ORG_TYPE_FACTORY);
        orgpo.setIsValid(ManageDictCodeConstants.STATUS_IS_VALID);
        orgpo.setIsDeleted(0);
    }

    @Override
    @Transactional(readOnly = true)
    public IPage<DealerInfoDTO> selectPageSaleInfo(Page<DealerInfoDTO> page, Map<String, Object> queryCondition) {
        // 获取总条数
        List<DealerInfoDTO> dealerinfodtos = dealerInfoMapper.selectPageSaleInfo(page, queryCondition);
        BrandCacheVO brandCacheVO = null;
        SeriesCacheVO seriesCacheVO = null;
        if (dealerinfodtos.size() > 0) {
            for (DealerInfoDTO dealerInfoDTO : dealerinfodtos) {
                if (dealerInfoDTO.getOrgId() == null) {
                    continue;
                }
                List<OrgBrandSeriesVO> list = orgMapper.getOrgBrandSeries(dealerInfoDTO.getOrgId().toString());
                if (list != null && !list.isEmpty()) {
                    for (int i = list.size() - 1; i > -1; i--) {
                        if (StringUtils.isEquals(list.get(i).getBillType(),
                                String.valueOf(SysAuthDictCodeConstants.BILL_TYPE_ORG_RELATION_BRAND))) {
                            brandCacheVO = baseCommonBrandService.getValueByBrandId(list.get(i).getBrandId().toString());
                            if (brandCacheVO != null) {
                                list.get(i).setBrandName(brandCacheVO.getBrandName());
                            } else {
                                list.remove(i);
                            }
                        } else {
                            seriesCacheVO = baseCommonSeriesService.getValueBySeriesId(list.get(i).getSeriesId().toString());
                            if (seriesCacheVO != null) {
                                list.get(i).setSeriesName(seriesCacheVO.getSeriesName());
                                list.get(i).setBrandId(seriesCacheVO.getBrandId());
                                list.get(i).setBrandName(seriesCacheVO.getBrandName());
                            } else {
                                list.remove(i);
                            }
                        }
                    }
                    dealerInfoDTO.setListOBSVO(list);
                }
            }
        }

        page.setRecords(dealerinfodtos);
        return page;
    }

    @Override
    public Integer addSaleInfoMaintain(DealerInfoDTO dealerInfoDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        LambdaQueryWrapper<DealerInfoPO> queryWrapper = new QueryWrapper<DealerInfoPO>().lambda();
        queryWrapper.eq(DealerInfoPO::getAppId, loginInfoDto.getAppId());
        queryWrapper.eq(DealerInfoPO::getCompanyId, dealerInfoDTO.getCompanyId());
        DealerInfoPO dealerinfopo1 = dealerInfoMapper.selectOne(queryWrapper);
        if (dealerinfopo1 != null) {
            throw new ServiceBizException("所选经销商公司下已经存在销售信息");
        }
        Long factoryCompanyId = companyMapper.findFactoryIdByAppId(loginInfoDto.getAppId());
        if (null == factoryCompanyId) {
            throw new ServiceBizException("您输入的AppID可能不存在");
        }
        DealerInfoPO dealerinfopo = new DealerInfoPO();
        dealerinfopo.setOrgId(Integer.MAX_VALUE);
        dealerinfopo.setAppId(loginInfoDto.getAppId());
        dealerinfopo.setCompanyId(dealerInfoDTO.getCompanyId());
        LambdaQueryWrapper<CompanyPO> queryWrapper1 = new QueryWrapper<CompanyPO>().lambda();
        queryWrapper1.eq(CompanyPO::getAppId, loginInfoDto.getAppId());
        queryWrapper1.eq(CompanyPO::getCompanyCode, dealerInfoDTO.getDealerCode());
        CompanyPO companypo1 = companyMapper.selectOne(queryWrapper1);
        //如果销售code和经销商code一样的话后面加上SA
        if (null != companypo1) {
            dealerinfopo.setDealerCode(dealerInfoDTO.getDealerCode());
        } else {
            dealerinfopo.setDealerCode(dealerInfoDTO.getDealerCode());
        }
        dealerinfopo.setDealerName(dealerInfoDTO.getDealerName());
        dealerinfopo.setDealerShortname(dealerInfoDTO.getDealerShortName());
        dealerinfopo.setOrgType(ManageDictCodeConstants.ORG_TYPE_DEALER);
        dealerinfopo.setDistributorLevel(dealerInfoDTO.getDistributorLevel());
        dealerinfopo.setAgType(dealerInfoDTO.getAgType());
        dealerinfopo.setTaxNo(dealerInfoDTO.getTaxNo());
        dealerinfopo.setValidStatus(dealerInfoDTO.getValidStatus());
        dealerinfopo.setBusinessStatus(dealerInfoDTO.getBusinessStatus());
        dealerinfopo.setFaxNo(dealerInfoDTO.getFaxNo());
        dealerinfopo.setLinkMan(dealerInfoDTO.getLinkMan());
        dealerinfopo.setPhone(dealerInfoDTO.getPhone());
        dealerinfopo.setZipCode(dealerInfoDTO.getZipCode());
        dealerinfopo.setSaleArea(dealerInfoDTO.getSaleArea());
        dealerinfopo.setProvinceId(dealerInfoDTO.getProvinceId());
        dealerinfopo.setCityId(dealerInfoDTO.getCityId());
        dealerinfopo.setCountyId(dealerInfoDTO.getCountyId());
        dealerinfopo.setAddress(dealerInfoDTO.getAddress());
        dealerinfopo.setLatitude(dealerInfoDTO.getLatitude());
        dealerinfopo.setLongitude(dealerInfoDTO.getLongitude());
        dealerinfopo.setFactoryCompanyId(factoryCompanyId.intValue());
        dealerinfopo.setStatus(10041001);
        dealerinfopo.setValidStatus(dealerInfoDTO.getValidStatus());
        dealerinfopo.setCreatedBy(loginInfoDto.getUserName());
        dealerinfopo.setUpdatedBy(loginInfoDto.getUserName());
        dealerInfoMapper.addSaleInfoMaintain(dealerinfopo);
        OrgPO orgpo = new OrgPO();
        orgpo.setAppId(loginInfoDto.getAppId());
        orgpo.setCompanyId(Long.valueOf(dealerInfoDTO.getCompanyId()));
        orgpo.setOrgCode(dealerinfopo.getDealerCode() + "SA");
        orgpo.setOrgName(dealerInfoDTO.getDealerName());
        orgpo.setOrgShortName(dealerInfoDTO.getDealerShortName());
        orgpo.setOrgType(ManageDictCodeConstants.ORG_TYPE_DEALER);
        orgpo.setDataType(ManageDictCodeConstants.DATA_TYPE_BY_OWNER);
        orgpo.setIsValid(dealerinfopo.getValidStatus());
        orgpo.setOrgId(Long.MAX_VALUE);
        orgMapper.insert(orgpo);
        updateDealOrgId(orgpo.getOrgId(), dealerinfopo.getDealerId());
        if (!StringUtils.isNullOrEmpty(dealerInfoDTO.getSaleArea())) {
            TrOrgPO trorgpo = new TrOrgPO();
            trorgpo.setOrgId(orgpo.getOrgId());
            trorgpo.setParentOrgId(Long.parseLong(dealerInfoDTO.getSaleArea()));
            trOrgMapper.insert(trorgpo);
        }
        //保存销售组织关系信息
        CompanyPO companypo = companyMapper.selectById(dealerinfopo.getCompanyId());
        TrOrgPO trorgpo = new TrOrgPO();
        trorgpo.setOrgId(orgpo.getOrgId());
        trorgpo.setParentOrgId(companypo.getOrgId().longValue());
        trOrgMapper.insert(trorgpo);
        List<OrgBrandSeriesVO> obsvo = dealerInfoDTO.getListOBSVO();
        if (null != obsvo && obsvo.size() > 0) {
            logger.info("进入车系品牌01：{}" + obsvo.toString());
            addAuthorizedBrand(orgpo.getOrgId(), dealerInfoDTO);
        }
        logger.info("标志:======================");
        // add
        CompanyPO company = companyMapper.selectById(dealerInfoDTO.getCompanyId());
        String companyCode = "";
        if (company != null) {
            companyCode = company.getCompanyCode();
        }
        Map<String, Object> data = new HashMap<>();
        data.put("appId", loginInfoDto.getAppId());
        data.put("ownerCode", dealerInfoDTO.getDealerCode());
        data.put("ownerParCode", dealerInfoDTO.getDealerCode());
        data.put("companyCode", companyCode);
        data.put("orgId", "");
        //远程调用对象：url / body参数（json）/  header
        MessEvent messEvent = new MessEvent();
        String channel = "sysParam";
        messEvent.setUrl("http://OPS-NOTIFY/notify/invoke/message?channel=" + channel);
        messEvent.setParam(data);
        messEvent.setHeaders(null);
        //远程调用
        iRemoteInvoke.sendPostWithTransaction(messEvent);

        return dealerinfopo.getDealerId();
    }

    public void updateDealOrgId(Long orgId, Integer dealId) {
        LambdaQueryWrapper<DealerInfoPO> queryWrapper = new QueryWrapper<DealerInfoPO>().lambda();
        queryWrapper.eq(DealerInfoPO::getDealerId, dealId);
        DealerInfoPO dealerinfopo = dealerInfoMapper.selectOne(queryWrapper);
        dealerinfopo.setOrgId(orgId.intValue());
        dealerInfoMapper.updateById(dealerinfopo);
    }

    //  添加授權品牌
    public Integer addAuthorizedBrand(Long orgId, DealerInfoDTO dealerInfoDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<OrgBrandSeriesVO> listobsvo = dealerInfoDTO.getListOBSVO();
        Integer byId;
        for (OrgBrandSeriesVO orgBrandSeriesVO : listobsvo) {
            if (null != orgBrandSeriesVO) {
                byId = trDealerOrgRelationMapper.selectByBillId(orgId.intValue(), orgBrandSeriesVO.getBrandId(), orgBrandSeriesVO.getSeriesId());
                if (null != byId) {
                    throw new DALException("授权已存在!");
                } else {
                    TrDealerOrgRelationPO trDealePo = new TrDealerOrgRelationPO();
                    if (orgBrandSeriesVO.getBillType() == SysAuthDictCodeConstants.BILL_TYPE_ORG_RELATION_BRAND) {
                        //存品牌id
                        trDealePo.setBillId(orgBrandSeriesVO.getBrandId().intValue());
                    } else { //存车系id
                        trDealePo.setBillId(orgBrandSeriesVO.getSeriesId().intValue());
                    }
                    trDealePo.setBillType(orgBrandSeriesVO.getBillType().intValue());
                    trDealePo.setOrgId(orgId.intValue());
                    trDealePo.setCreatedBy(loginInfoDto.getUserName());
                    trDealePo.setUpdatedBy(loginInfoDto.getUserName());
                    trDealerOrgRelationMapper.addAuthorizedBrand(trDealePo);
                    logger.info("车系品牌数据：{}" + trDealePo.toString());
                }
            }
        }
        return orgId.intValue();
    }

    /**
     * 根据orgid 和name取code
     *
     * @param orgId
     * @param ownerName
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/10/24
     */
    @Override
    public List<DealerInfoDTO> getDealerByorgId(String orgId, String ownerName) {
        if (null == orgId && null == ownerName) {
            throw new ServiceBizException("不支持获取全量数据");
        }

        List<DealerInfoPO> dealerinfo = this.dealerInfoMapper.getDealerByorgId(orgId, ownerName);
        return dealerinfo == null ? null : BeanMapperUtil.copyList(dealerinfo, DealerInfoDTO.class);
    }

    /**
     * 车厂通过组织id（大区小区类型的组织）获取本车厂下对应的经销商
     *
     * @param orgId
     * @param:
     * @return: 车厂通过组织id（大区小区类型的组织）获取本车厂下对应的经销商
     * @auther: 马邢健
     * @since: 2019/10/31
     */
    @Override
    public List<DealerOrgAreaVO> getDealerBySaleArea(@Param("orgId") String orgId, @Param("dealerCode") String dealerCode, @Param("dealerName") String dealerName) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return dealerInfoMapper.getDealerBySaleArea(orgId, loginInfoDto.getCompanyId().toString(), loginInfoDto.getAppId(), dealerCode, dealerName);
    }

    /**
     * 获取经销商公司的 经销商类型
     *
     * @param:
     * @return:
     * @auther: 李贺
     * @since: 2019/11/4
     */
    @Override
    public Integer getDealerType() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appId = loginInfoDto.getAppId();
        Long factoryIdByAppId = companyMapper.findFactoryIdByAppId(appId);
        return companyMapper.findDealerTypeById(factoryIdByAppId);
    }

    /**
     * 是否有售后
     *
     * @param:
     * @return:
     * @auther: 李贺
     * @since: 2019/11/4
     */
    @Override
    public Integer afterSale() {
        Integer dealerType = getDealerType();
        if (dealerType == null) {
            return 10041002;
        }
        if (dealerType.equals(25381001) || dealerType.equals(25381003) || dealerType.equals(10041001)) {
            return 10041001;
        }
        return 10041002;
    }


    /**
     * 根据条件查询经销商code
     *
     * @auther: 李贺
     * @since: 2019/11/13
     */
    @Override
    public List<DealerInfoParentVO> getDealerInfos(Long orgId, Long provinceId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return dealerInfoMapper.getDealerInfos(orgId, provinceId, loginInfoDto.getAppId());
    }


    /**
     * 根据省市区查询经销商信息
     *
     * @auther: 李贺
     * @since: 2019/11/15
     */
    @Override
    public List<DealerInfoParentVO> getDealerByCity(Integer provinceId, Integer cityId, Integer countyId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return dealerInfoMapper.getDealerByCity(provinceId, cityId, countyId, loginInfoDto.getAppId());
    }

    /**
     * DEALERCODE批量获取ORGID
     *
     * @param orgId
     * @param appId
     * @param dealerCodes
     * @param companyId
     * @param dealerName
     * @return
     * @auth tanjie
     */
    @Override
    public List<DealerOrgAreaVO> getDealerBysaleAreaBatch(String orgId, String appId, List<String> dealerCodes, Long companyId, String dealerName) {
        List<DealerOrgAreaVO> result = new ArrayList<>();
        LoginInfoDto beanByType = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        beanByType.setCompanyId(companyId);
        beanByType.setAppId(appId);

        //查询全部经销商信息（转成Map）
        List<DealerOrgAreaVO> dealerOrgArea = dealerInfoMapper.getDealerBySaleArea(null,null,appId,null,null);

        Map<String,DealerOrgAreaVO> dealerOrgAreaMap = Maps.newHashMap();
        dealerOrgArea.stream().forEach(e-> {
//		    dealerOrgAreaMap.put(e.getOrgId() + "-" + e.getCompanyId() + "-" + e.getDealerCode() + "-" + e.getDealerName() ,e);
            dealerOrgAreaMap.put(e.getDealerCode(),e);
        });



        for (String dealerCode : dealerCodes) {
            DealerOrgAreaVO dealerBySaleArea = dealerOrgAreaMap.get(dealerCode);
//            List<DealerOrgAreaVO> dealerBySaleArea = this.getDealerBySaleArea(orgId, dealerCode, dealerName);
            if (!ObjectUtils.isEmpty(dealerBySaleArea)) {
//                DealerOrgAreaVO dealerOrgAreaVO = dealerBySaleArea.get(0);
                result.add(dealerBySaleArea);
            }
        }
        return result;
    }

    /**
     * 获得所有经销商信息
     *
     * @auther: 李贺
     */
    @Override
    public List<DealerInfoParentVO> getAllDealer(String orgId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<DealerInfoPO> poQueryWrapper = new QueryWrapper<>();
        poQueryWrapper.eq("app_id", loginInfoDto.getAppId()).eq("SALE_AREA", orgId);
        List<DealerInfoPO> dealerinfopos = dealerInfoMapper.selectList(poQueryWrapper);
        return BeanMapperUtil.copyList(dealerinfopos, DealerInfoParentVO.class);
    }

    /**
     * 获得所有经销商通过ownercode
     *
     * @auther: maxingjian
     */
    @Override
    public DealerInfoAVO getDealerByOwner(String ownerCode) {
        LoginInfoDto login = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return dealerInfoMapper.getDealerByOwner(ownerCode, login.getAppId());
    }

    @Override
    public DealerInfoDTO querytDealerInfo(Long dealerId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        DealerInfoDTO dealerInfoDTO = dealerInfoMapper.querytDealerInfo(dealerId, loginInfoDto.getAppId());
        List<OrgBrandSeriesVO> list = orgMapper.getOrgBrandSeries(dealerInfoDTO.getOrgId().toString());
        dealerInfoDTO.setListOBSVO(list);
        return dealerInfoDTO;
    }

    /**
     * 获取所有经销商
     * 李贺
     */
    @Override
    public List<DealerOrgVO> dealerByCityOrArea(Integer provinceId, Integer cityId, String orgId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return dealerInfoMapper.dealerByCityOrArea(provinceId, cityId, orgId, loginInfoDto.getAppId());
    }

    @Override
    public List<DealerDTO> getAllDealerCode(String appId) {
        LambdaQueryWrapper<DealerInfoPO> dealerQuery = new QueryWrapper<DealerInfoPO>().lambda().eq(DealerInfoPO::getAppId, appId);
        List<DealerInfoPO> dealerinfopos = dealerInfoMapper.selectList(dealerQuery);
        return null == dealerinfopos ? null : BeanMapperUtil.copyList(dealerinfopos, DealerDTO.class);
    }

    /**
     * 获得经销商所属区域
     * 李贺
     *
     * @param
     * @return
     */
    @Override
    public List<OrgParentVO> getSaleArea(List<Long> dealerIds) {
        return dealerInfoMapper.getSaleArea(dealerIds);
    }

    /**
     * 保存经销商营业时间和门店图片
     * <p>
     * 李贺
     */
    @Override
    public void setDealerPicture(DealerPictureVO dealerPictureVO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        LambdaQueryWrapper<DealerInfoPO> queryWrapper = new QueryWrapper<DealerInfoPO>().lambda();
        queryWrapper.eq(DealerInfoPO::getDealerCode, dealerPictureVO.getDealerCode()).eq(DealerInfoPO::getCompanyId, loginInfoDto.getCompanyId());
        DealerInfoPO dealerinfopo = dealerInfoMapper.selectOne(queryWrapper);
        if (dealerinfopo != null) {
            BeanMapperUtil.copyProperties(dealerPictureVO, dealerinfopo);
        }
        dealerInfoMapper.updateById(dealerinfopo);
    }

    /**
     * 获取经销商营业时间和门店图片
     * <p>
     * 李贺
     */
    @Override
    public List<DealerPictureVO> getDealerPictures(String dealerIds, String dealerCodes) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<String> dealerIdList = null;
        List<String> dealerCodeList = null;
        if (!StringUtils.isNullOrEmpty(dealerIds)) {
            dealerIdList = Arrays.asList(dealerIds.split(","));
        }
        if (!StringUtils.isNullOrEmpty(dealerCodes)) {
            dealerCodeList = Arrays.asList(dealerCodes.split(","));
        }
        List<DealerPictureVO> dealerPictures = dealerInfoMapper.getDealerPictures(dealerIdList, dealerCodeList, loginInfoDto.getAppId());
        if (CollectionUtils.isEmpty(dealerPictures)) {
            return null;
        }
        for (DealerPictureVO dealerPicture : dealerPictures) {
            if (StringUtils.isNullOrEmpty(dealerPicture.getDealerPicture())) {
                dealerPicture.setDealerPicture(dealerPictureUrl);
            }
        }
        return dealerPictures;
    }

    /**
     * 获取所有销售部门
     * <p>
     * 李贺
     */
    @Override
    public List<Long> listDealerOrgs() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<Long> dealerOrgIds = dealerInfoMapper.findDealerOrgId(loginInfoDto.getCompanyId());
        if (CollectionUtils.isEmpty(dealerOrgIds)) {
            return null;
        }
        StringBuilder orgs = new StringBuilder();
        for (Long dealerOrgId : dealerOrgIds) {
            orgs.append(orgMapper.getOrgs(dealerOrgId)).append(",");
        }
        return Arrays.stream(orgs.toString().split(",")).map(Long::parseLong).collect(Collectors.toList());
    }

    @Override
    public DealerOrAscOrCompanyVO getCompanyByCodeOrName(String ownerCode) {

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<DealerOrAscOrCompanyVO> dealerorascorcompanyvos = new ArrayList<>();
        if (ownerCode == null) {
            ownerCode = loginInfoDto.getOwnerCode();
        }
        dealerorascorcompanyvos = dealerInfoMapper.getDealerByCodeOrName(ownerCode);
        if (dealerorascorcompanyvos.size() != 1) {
            dealerorascorcompanyvos = dealerInfoMapper.getAscByCodeOrName(ownerCode);
            if (dealerorascorcompanyvos.size() != 1) {
                dealerorascorcompanyvos = dealerInfoMapper.getCompanyByCodeOrName(ownerCode);
            }
        }
        return dealerorascorcompanyvos.get(0);
    }

}
